import {Component, OnInit, QueryList, SimpleChange, SimpleChanges, ViewChildren} from '@angular/core';
import {ChartsService} from './charts.servece';
import {QuestionNumModel, TotalDataModel} from './model/questionNum.model';
import {BaseChartDirective} from "ng2-charts";

@Component({
  selector: 'app-charts',
  templateUrl: 'charts.component.html',
  styleUrls: ['./charts.component.less'],
  providers: [ChartsService]
})

export class ChartsComponent implements OnInit {
  @ViewChildren(BaseChartDirective) charts: QueryList<BaseChartDirective>;


  queryType = 'week';
  oldQueryType = 'week';
  totalData: TotalDataModel = new TotalDataModel;
  constructor(private chartsService : ChartsService) {}
  public doughnutChartLabels: string[] = ['合格人数', '不合格人数'];
  public doughnutChartData: number[] = [350, 450];
  public doughnutChartType: string = 'doughnut';

  public doughnutChartOptions: any = {
    title:{
      display: true,
      position: 'top',
      fontSize: 24,
      fontFamily: 'Helvetica',
      fontStyle: 'bold',
      padding: 10,
      lineHeight: 1.2,
      text: '答题通过率'
    }

  }

  public lineChartOptions: any = {
    title:{
      display: true,
      position: 'top',
       fontSize: 24,
       fontFamily: 'Helvetica',
       fontStyle: 'bold',
       padding: 10,
       lineHeight: 1.2,
      text: '答题数统计'
    }
  }

  public lineChartData:Array<any> = [{data:[], label:'答题人数'}];
  public lineChartLabels:string[] = [];
  public lineChartType:string = 'line';
  public lineChartLegend:boolean = false;
  // events
  public chartClicked(e: any): void {
    console.log(e);
  }

  public chartHovered(e: any): void {
    console.log(e);
  }

  ngOnInit() {
    this.getTotalData();
    this.questionNum();
  }
  typeChange() {
    if (this.queryType !== this.oldQueryType){
      this.oldQueryType = this.queryType;
      this.questionNum();
    }
  }

  getTotalData() {
    this.chartsService.getTotalData().then((response: TotalDataModel) => {
      this.totalData = response;
      this.createBarData(response);
    });
  }

  questionNum() {
    this.chartsService.getQuestionNum({queryType: this.queryType}).then((response: QuestionNumModel) => {
      this.createCharsData(response);
    });
  }

  createCharsData (data: QuestionNumModel) {
    console.log(data)
    let labels = data.timeList;
    this.lineChartData = [
      {data: data.dataList, label: '曲线'}
    ];
    console.log(this.lineChartData);
    this.charts.forEach((child) => {
      if (child.chartType == 'line') {
        child.labels.splice(0);
        child.labels = labels;
        child.ngOnChanges({} as SimpleChanges);
      }
    })
  }

  createBarData(response: TotalDataModel) {
    this.doughnutChartData = [response.qualifiedSum, response.disQualifiedSum];
  }
}





